import { useRef, useEffect, useState } from "react";

const HomeStore = (props: any) => {
  const { list, handleClickOpen } = props;

  const [caseList, setCaseList] = useState(list);
  const [position, setPosition] = useState({ x: 0, y: 0, show: "none" });
  const [currDinosaur, setCurrDinosaur] = useState({
    id: -1,
    path: "",
    grade: 0,
    has: false,
  } as any);

  const [endDinosaur, setEndDinosaur] = useState({
    id: -1,
    path: "",
    grade: 0,
    has: false,
  } as any);

  // 容器对象
  const myRef = useRef(null);
  // setCurrDinosaur({});
  // console.log(1111, currDinosaur, endDinosaur);

  /**
   * 判断恐龙移动还是合并
   */
  if (
    endDinosaur.id !== -1 &&
    currDinosaur.id !== -1 &&
    endDinosaur.id != currDinosaur.id
  ) {
    setCaseList(() =>
      caseList.map((item: any) => {
        if (
          (item.id === endDinosaur.id || item.id === currDinosaur.id) &&
          endDinosaur.id !== currDinosaur.id &&
          currDinosaur.id !== -1 &&
          endDinosaur.id !== -1
        ) {
          // return { ...item, grade: currDinosaur.grade + 1 };
          if (
            endDinosaur.grade == currDinosaur.grade &&
            currDinosaur.has &&
            endDinosaur.has
          ) {
            if (item.id == endDinosaur.id) {
              return { ...item, grade: currDinosaur.grade + 1 };
            } else if (item.id === currDinosaur.id) {
              return { ...item, has: false };
            } else {
              return item;
            }
          } else {
            if (item.id == endDinosaur.id) {
              return { ...currDinosaur };
            } else if (item.id == currDinosaur.id) {
              return { ...endDinosaur };
            } else {
              return item;
            }
          }
        } else {
          return item;
        }
      })
    );
    setCurrDinosaur({
      id: -1,
      path: "",
      grade: 0,
    });
    setEndDinosaur({
      id: -1,
      path: "",
      grade: 0,
    });
  }

  // console.log("列表数据:", caseList);

  useEffect(() => {
    // 当组件挂载后，可以通过myRef.current访问到对应的DOM元素
    if (myRef.current) {
      // console.log(myRef.current)
      // 操作DOM元素，例如改变颜色
      const obj = myRef.current as any;

      const list_length = caseList.length;
      // 容器滚动条
      // let box_scrollTop = 0;
      // 容器宽度
      const window_width = document.documentElement.scrollWidth;
      // 容器高度
      const window_height = document.documentElement.scrollHeight;
      // 容器宽度
      // let box_width = 0;
      // 容器高度
      // let box_height = 0;
      // 容器距上面的位置
      let box_top = 0;
      // 容器距左边的位置
      let box_left = 0;
      // 小格子宽度
      let min_box_width = 0;
      // ul宽度
      let ul_width = 0;
      // ul高度
      // let ul_height = 0;
      // 鼠标开始X坐标
      let start_x = 0;
      // 鼠标开始Y坐标
      let start_y = 0;
      // 鼠标移动X坐标
      let move_x = 0;
      // 鼠标移动Y坐标
      let move_y = 0;
      // 是否拖动
      // let isMove = false;
      // 是否滚动条
      // let isScroll = true;
      // 差值宽
      let differ_w = 0;
      // 差值高
      let differ_h = 0;
      let curr_index = -1;

      // const clientRect = obj.getBoundingClientRect();
      const ul = obj.querySelector("ul").getBoundingClientRect();
      // console.log(ul);
      // box_width = ul.width;
      // box_height = ul.height;
      box_top = ul.top;
      box_left = ul.left;
      ul_width = ul.width;
      // ul_height = ul.height;
      min_box_width = ul_width / 4;

      // const handleResize = () => {
      //   // setWindowWidth(window.innerWidth);
      //   window_width = window.innerWidth;
      //   window_height = window.innerHeight;
      // };

      /**
       * 触摸事件
       * @param e
       */
      const handleStart = (e: any) => {
        e.preventDefault();
        if (curr_index == -1) {
          start_x = e.touches[0].clientX;
          start_y = e.touches[0].clientY;
          const x_index = Math.floor((start_x - box_left) / min_box_width);
          const y_index = Math.floor((start_y - box_top) / min_box_width);
          differ_w = start_x - (box_left + min_box_width * x_index);
          differ_h = start_y - (box_top + min_box_width * y_index);
          const _i = y_index * 4 + x_index;
          if (_i < list_length && _i >= 0) {
            const currItem = caseList[_i];
            const _has = currItem["has"];
            if (_has) {
              // isMove = true;
              setCurrDinosaur({ ...currItem });
              curr_index = _i;
            }
          }
        }
      };

      /**
       * 移动事件
       * @param e
       */
      const handleMove = (e: any) => {
        if (curr_index !== -1) {
          move_x = e.touches[0].clientX - differ_w;
          move_y = e.touches[0].clientY - differ_h;
          if (move_x > window_width - min_box_width - 10) {
            move_x = window_width - min_box_width - 10;
          }
          if (move_x < 0) {
            move_x = 0;
          }
          if (move_y > window_height - min_box_width) {
            move_y = window_height - min_box_width;
          }
          if (move_y < 0) {
            move_y = 0;
          }
          setPosition({ x: move_x, y: move_y, show: "block" });
        }
      };

      /**
       * 离开事件
       * @param e
       * @returns
       */
      const handleEnd = (e: any) => {
        if (curr_index !== -1) {
          start_x = e.changedTouches[0].clientX;
          start_y = e.changedTouches[0].clientY;
          const x_index = Math.floor((start_x - box_left) / min_box_width);
          const y_index = Math.floor((start_y - box_top) / min_box_width);
          differ_w = start_x - (box_left + min_box_width * x_index);
          differ_h = start_y - (box_top + min_box_width * y_index);

          if (x_index < 4 && y_index < 3 && x_index >= 0 && y_index >= 0) {
            const _i = y_index * 4 + x_index;
            const endItem = caseList[_i];
            setEndDinosaur({ ...endItem });
          } else {
            setCurrDinosaur({
              id: -1,
              path: "",
              grade: 0,
              has: false,
            });
          }
          curr_index = -1;
          setPosition({ x: 0, y: 0, show: "none" });
        }
      };

      // 按下事件
      obj.addEventListener("touchstart", handleStart);

      // 移动事件
      document.addEventListener("touchmove", handleMove, { passive: false });

      // 弹起事件
      obj.addEventListener("touchend", handleEnd);

      // 滚动事件
      obj.addEventListener("scroll", (e: any) => {
        // box_scrollTop = e.target.scrollTop;
        console.log(e);
      });

      // window.addEventListener("resize", handleResize);
      return () => {
        obj.removeEventListener("touchstart", handleStart);
        document.removeEventListener("touchmove", handleMove);
        obj.removeEventListener("touchend", handleEnd);
      };
    }
  }, [caseList]);

  return (
    <div className="home-store">
      <div className="btn-list">
        <ul>
          <li className="li-btn">幸运转盘</li>
          <li className="li-btn">福利中心</li>
          <li className="li-btn">福利中心</li>
          <li className="li-btn">
            整点金币<div className="reminder">99</div>
          </li>
        </ul>
      </div>
      <div className="case-list-box">
        <div className="list-box" ref={myRef}>
          {/* 移动框 */}
          <div
            className="move-box"
            style={{
              left: position.x + "px",
              top: position.y + "px",
              display: position.show,
            }}
          >
            <img src={"/images/dinosaur/" + currDinosaur.grade + ".png"} />
            <div className="grade">{currDinosaur.grade}</div>
          </div>
          {/* 列表 */}
          <ul className="ul-list">
            {caseList.map((item: any) => (
              <li key={item.id} className="li-box">
                <div
                  className={
                    item.has
                      ? item.id == currDinosaur.id
                        ? "case-box has lift"
                        : "case-box has"
                      : "case-box"
                  }
                  data-id={item.id}
                >
                  {item.has ? (
                    <img
                      className="dinosaur-img"
                      src={"/images/dinosaur/" + item.grade + ".png"}
                    />
                  ) : (
                    <img className="case-add" src="./images/case_box_add.png" />
                  )}
                  <div className="grade">{item.grade}</div>
                </div>
              </li>
            ))}
          </ul>
        </div>
        <div className="case-bottom-box">
          <div className="btn-left" onClick={handleClickOpen}>
            <img src="./images/home_btn_3.png" />
          </div>
          <div className="btn-center">
            <div className="title">立即购买</div>
            <div className="all-number">次数 29/100</div>
          </div>
          <div className="btn-right">
            <img src="./images/home_btn_1.png" />
          </div>
        </div>
      </div>
    </div>
  );
};
export default HomeStore;
